package org.dubnation.base.util;

import org.dubnation.base.enums.ResponseCode;
import org.dubnation.user.rabbitmq.entity.SendEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件工具类
 */
public class SendEmailUtil {

    private static JavaMailSender javaMailSender;
    @Autowired
    public void setJavaMailSender(JavaMailSender javaMailSender){
        SendEmailUtil.javaMailSender = javaMailSender;
    }

    public static Boolean sendEmail(SendEntity sendEntity) {
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //获取发送复杂邮件工具类
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            //发送者
            messageHelper.setFrom(sendEntity.getFrom());
            //接收者
            messageHelper.setTo(sendEntity.getTo());
            //发送主题
            messageHelper.setSubject(sendEntity.getSubject());
            /*
             * 发送html文本
             * 发送的激活地址中需要携带参数--shopId和employeeId--用redis封装
             * */
            messageHelper.setText(sendEntity.getContent(), true);
            //发送
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            try {
                throw new MessagingException(ResponseCode.RESPONSE_CODE_400006.getMessage());
            } catch (MessagingException messagingException) {
                messagingException.printStackTrace();
                return false;
            }
        }
        return true;
    }
}
